package hot;

/**
 * @author way
 * @create 2025-03-10 21:56
 */
public class _25_reverseKGroup {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head);
        int n = 0;
        ListNode cur = dummy;
        ListNode p = dummy;
        while (cur.next != null) {
            n++;
            cur = cur.next;
        }

        cur = head;
        ListNode pre = null;
        for (; n >= k; n -= k) {
            for (int i = 0; i < k; i++) {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
            }

            ListNode temp = p.next;
            p.next.next = cur;
            p.next = pre;
            p = temp;


        }
        return dummy.next;

    }
}
